import Request from '@/common/request.js'

const zhttp = new Request();

export default class autoPage {
	/**
	 * 自动分页
	 * @param {string}  url  请求地址
	 * @param {string}  limit  美页显示条数
	 * @param {function}  resOperating  对返回的结果进行其它的操作
	 * @param {arrow}  useData  要使用返回的字段(数据列表)，
	 * @param {arrow}  useTolNum  要使用返回的字段(数据总条数)，
	 * @param {object}  otherArg  请求附带的其他参数
	 */
	constructor(url, limit = 20, otherArg = {}, resOperating, useData = 'data.list', useTolNum = 'data.page.total') {
		this.cureentPage = 1;
		this.limit = limit;
		this.dataTolNum = 0;
		this.url = url;
		this.otherArg = otherArg;
		this.dataList = [];
		this.useData = useData;
		this.useTolNum = useTolNum;
		this.resOperating = resOperating;
		this.isFilter = true; //是否验证相应码
		this.isShowCenterLodin = true;
		this.isSetNoDataSty = true; //是否使用自定义无数据样式  
	}
	/**
	 * 请求数据
	 * @return {object} moreData 请求的其它参数
	 * @param {function}  resOperating  对返回的结果进行其它的操作F
	 * @return {object} 请求的数据  dataList是分页获取的总数居
	 */
	async pagination(moreData = {}, resOperating) {
		if (resOperating) {
			this.resOperating = resOperating;
		}
		moreData = {
			...this.otherArg,
			...moreData
		};
		let res = await zhttp.Request(this.url, {
			page: this.cureentPage,
			list_rows: this.limit,
			...moreData
		}, this.isShowCenterLodin, this.isFilter);
		try {
			uni.stopPullDownRefresh();
		} catch (e) {}
		if (res.code != 1) {
			if (!this.isSetNoDataSty) {
				uni.showToast({
					title: '暂未查到相关信息~',
					icon: "none",
					duration: 2000
				});
			}
			return 'noData';
		}

		// try {
		// 赋值
		// const useData = this.useData;
		// const useTolNum = this.useTolNum;
		//数据赋值 
		let tempU = res;
		let useDatas = this.useData.split('.');
		useDatas.forEach((item) => {
			tempU = tempU[item];
		});
		if (this.resOperating) {
			this.resOperating(tempU);
		}
		this.dataList.push(...tempU);
		//总条数赋值·
		let tempT = res;
		let useTolNums = this.useTolNum.split('.');
		useTolNums.forEach((item) => {
			tempT = tempT[item];
		});
		this.dataTolNum = tempT;
		// } catch (e) {
		// 	throw new Error('autoPage======>：使用的字段不存在，请检查数据结构是否正确！',e)
		// }
		res.dataList = this.dataList;
		return res;
	}
	// 加载更多
	/**
	 *  加载更多
	 * @param {Boolean} customizeLoadMore  是否使用自定义无数据
	 */
	zloadMore(customizeLoadMore) {
		if (this.cureentPage * this.limit < this.dataTolNum) {
			++this.cureentPage;
			return this.pagination();
		} else {
			if (!customizeLoadMore) {
				uni.showToast({
					title: '没有更多了~',
					icon: 'none'
				});
			}
			return 'noMore';
		}
	}
	/**
	 * 刷新/重置数据
	 * @param {Boolean}  = [true]  isResh   是否刷新数据
	 */
	resetData(isResh = true) {
		this.cureentPage = 1;
		this.dataTolNum = 0;
		this.dataList = [];
		if (isResh) {
			return this.pagination();
		}
	}
}
